package com.fddh.springboot.filter;

import org.springframework.core.annotation.Order;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

/**
 * 前端接口请求节流util
 */
@Order(1)
@WebFilter(filterName = "IpCountFilter",urlPatterns={"/*"})
public class IpCountFilter implements Filter {

    private final static String sessionKey = "SESSION_IP_COUNT";
    private final static int maxRequest = 1;   //最大次数
    private final static int time=2000;       //时间段（毫秒）

    @Override
    public void init(FilterConfig arg0)
            throws ServletException {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("进入过滤器");
        HttpServletRequest req = (HttpServletRequest) request;
        IpCount t = (IpCount) req.getSession().getAttribute(sessionKey);
        if(t == null){
            t = new IpCount();
            t.setFirstTime(System.currentTimeMillis());
            t.setTimes(1);
            req.getSession().setAttribute(sessionKey, t);
            System.out.println("第一次进入过滤器 "+t.getTimes());
            chain.doFilter(request, response);
        }else{
            if(System.currentTimeMillis()-t.getFirstTime()<=time){
                t.setTimes(t.getTimes()+1);
                if(t.getTimes()<=maxRequest){
                    System.out.println("一：小于规定时间内的请求次数—放行:"+t.getTimes());
                    // t.setTimes(t.getTimes()+1);
                    req.getSession().setAttribute(sessionKey, t);
                    chain.doFilter(request, response);
                }else{
                    System.out.println("超过了规定时间内的请求次数 "+t.getTimes());
                }
            }else{
                t.setFirstTime(System.currentTimeMillis());
                t.setTimes(1);
                req.getSession().setAttribute(sessionKey, t);
                System.out.println("二：小于规定时间内的请求次数—放行:"+t.getTimes());
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }
}
class IpCount{
    private long firstTime;
    private int times;
    public long getFirstTime() {
        return firstTime;
    }
    public void setFirstTime(long firstTime) {
        this.firstTime = firstTime;
    }
    public int getTimes() {
        return times;
    }
    public void setTimes(int times) {
        this.times = times;
    }
}
